package com.example.demo.controller;

import com.example.demo.commen.AjaxResult;
import com.example.demo.commen.Constant;
import com.example.demo.commen.SecurityUtil;
import com.example.demo.model.Userinfo;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.security.Security;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * user:likai
 * Date:2023-02-14
 * Time:10:54
 */
//返回的是数据
@RestController
@RequestMapping("/user")
public class UserContrller {

    //注入服务层
    @Autowired
    private UserService userService;

    @RequestMapping("/reg")
    public Object reg(String username,String password){
        if(!StringUtils.hasLength(username)||!StringUtils.hasLength(password)){
            return AjaxResult.fail(-1,"非法参数");
        }
        //添加
        int result=userService.add(username,
                SecurityUtil.encrypt(password));
        if(result==1){
            return AjaxResult.success("添加成功",1);
        }
        return AjaxResult.fail(-1,"添加失败");
    }
    @RequestMapping("/login")
    public int login(HttpServletRequest request,String username, String password){
        if(!StringUtils.hasLength(username)||!StringUtils.hasLength(password)){
            return 0;
        }
        //查找
        Userinfo userinfo=userService.getUserByName(username);
        if(userinfo==null||userinfo.getId()<0){
            return -1;
        }else {
            boolean result = SecurityUtil.decrypt(password, userinfo.getPassword());
            if (result) {
                //登陆成功之后保存session
                HttpSession session = request.getSession();
                session.setAttribute(Constant.SESSION_USERINFO_KEY, userinfo);
                return 1;
            }
        }
        return -1;
    }
    @RequestMapping("/logout")
    public boolean logout(HttpServletRequest request){
        HttpSession session= request.getSession(false);
        if(session!=null&&session.getAttribute(Constant.SESSION_USERINFO_KEY)!=null){
            session.removeAttribute(Constant.SESSION_USERINFO_KEY);
        }
        return true;
    }

    @RequestMapping("/myinfo")
    public Userinfo userinfo(HttpServletRequest request){
        HttpSession session= request.getSession(false);
        if(session!=null&&session.getAttribute(Constant.SESSION_USERINFO_KEY)!=null){
            return (Userinfo) session.getAttribute(Constant.SESSION_USERINFO_KEY);
        }
        return null;
    }
    @RequestMapping("/myinfobyuid")
    public Userinfo myinfobyuid(Integer uid){
        if(uid!=null&&uid>0){
            return userService.selectById(uid);
        }
        return null;
    }

}
